package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Dict;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.DictMapper;
import com.sskj.api.service.IDictItemService;
import com.sskj.api.service.IDictService;
import com.sskj.api.vo.req.DictPageListReq;
import com.sskj.common.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class DictService extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Autowired
    private IDictItemService dictItemService;

    @Override
    public void add(Dict dict) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getCode, dict.getCode()).or().eq(Dict::getName, dict.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("字典已存在");
        }
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        removeById(id);
        dictItemService.deleteByDictId(id);
    }

    @Override
    public void update(Dict dict) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Dict::getId, dict.getId()).and(consumer -> {
            consumer.eq(Dict::getCode, dict.getCode()).or().eq(Dict::getName, dict.getName());
        });
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("字典已存在");
        }

        updateById(dict);
    }

    @Override
    public IPage<Dict> pageList(DictPageListReq req) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Dict::getId);
        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(Dict::getName, req.getName());
        }
        if (req.getStatus() != null && req.getStatus() >= 0) {
            lambdaQueryWrapper.eq(Dict::getStatus, req.getStatus());
        }

        IPage<Dict> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return page(pageConfig, lambdaQueryWrapper);
    }
}
